package cn.keepme.ep.member.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.subject.Subject;
import org.jweb.core.bean.ReplyDataMode;
import org.jweb.core.util.Md5Util;
import org.jweb.core.util.ReplyCodeResourceUtil;
import org.jweb.core.util.StringUtil;
import org.jweb.core.web.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.keepme.ep.auth.entity.TSRole;
import cn.keepme.ep.auth.entity.TSRoleUser;
import cn.keepme.ep.auth.entity.TSUser;
import cn.keepme.ep.auth.transfer.vo.authen.AuthUserVO;
import cn.keepme.ep.common.service.SMSServiceI;
import cn.keepme.ep.common.service.SysServiceI;
import cn.keepme.ep.member.entity.FunctionEntity;
import cn.keepme.ep.member.entity.GeneralUserEntity;
import cn.keepme.ep.member.entity.RoleAndFunctionEntity;
import cn.keepme.ep.member.entity.RoleEntity;
import cn.keepme.ep.member.entity.UserAndRoleEntity;
import cn.keepme.ep.member.entity.UserCategoryEntity;
import cn.keepme.ep.member.transfer.form.member.MemberRegistForm;
import cn.keepme.ep.util.MemberUtil;

@Controller
@RequestMapping("/member")
public class MemberController extends BaseController {

	@Autowired
	private SysServiceI sysService;
	@Autowired
	private SMSServiceI smsService;
	@Autowired
	private EhCacheManager ehcacheCacheManager;

	@RequestMapping(value = "/regist")
	@ResponseBody
	public ReplyDataMode regist(MemberRegistForm saveForm,
			HttpServletRequest req) {
		ReplyDataMode j = new ReplyDataMode();

		if (!MemberUtil.validSMSCode(saveForm.getMphone(),
				saveForm.getValidCode(), ehcacheCacheManager)) {
			j.setSuccess(false);
			j.setStatusCode(ReplyCodeResourceUtil
					.getProperties("regist_validCode_error"));
			return j;
		}
		// 验证手机号是否被注册过
		GeneralUserEntity tempUser = this.sysService.findUniqueByProperty(
				GeneralUserEntity.class, "mphone", saveForm.getMphone());
		if (tempUser != null) {
			j.setSuccess(false);
			j.setStatusCode(ReplyCodeResourceUtil
					.getProperties("regist_mphone_registed"));
			j.setSuccess(false);
			return j;
		}
		TSUser tempTSUser = this.sysService.findUniqueByProperty(TSUser.class,
				"mobilePhone", saveForm.getMphone());
		if (tempTSUser != null) {
			j.setSuccess(false);
			j.setStatusCode(ReplyCodeResourceUtil
					.getProperties("regist_mphone_registed"));
			j.setSuccess(false);
			return j;
		}

		GeneralUserEntity userEntity = (GeneralUserEntity) saveForm.toEntity();
		userEntity.setPwd(Md5Util.getMD5(userEntity.getPwd()));
		this.sysService.saveOrUpdate(userEntity);
		// 默认加载所有喊单权限
		UserCategoryEntity ucEntity = null;
		String sql = "select  t1.category_code from tp_analyze_category t1 where t1.parent_category_id is not null";
		List<String> ucList = this.sysService.findListbySql(sql);
		for (String u : ucList) {
			ucEntity = new UserCategoryEntity();
			ucEntity.setTradeRoomIdStatus("1");
			ucEntity.setGeneralUserId(userEntity.getMphone());
			ucEntity.setCategoryCode(u);
			this.sysService.saveOrUpdate(ucEntity);
		}

		j.setSuccess(true);
		return j;
	}

	@RequestMapping(value = "/sendSMSValidCode")
	@ResponseBody
	public ReplyDataMode sendSMSValidCode(String mphone, HttpServletRequest req) {
		// 验证手机号是否被注册过
		GeneralUserEntity tempUser = this.sysService.findUniqueByProperty(
				GeneralUserEntity.class, "mphone", mphone);
		if (tempUser != null) {
			ReplyDataMode j = new ReplyDataMode();
			j.setSuccess(false);
			j.setStatusCode(ReplyCodeResourceUtil
					.getProperties("regist_mphone_registed"));
			j.setSuccess(false);
			return j;
		}
		ReplyDataMode mode = MemberUtil.sendSMSValidCode(mphone,
				req.getLocale(), smsService, ehcacheCacheManager);
		return mode;
	}

	/**
	 * 返回登陆用户权限列表和角色列表
	 * 
	 * @param content
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/permissions")
	@ResponseBody
	@RequiresAuthentication
	public ReplyDataMode permissions(String content, HttpServletRequest req) {
		ReplyDataMode j = new ReplyDataMode();
		Set<String> roleNames = new HashSet<String>();
		Set<String> permissions = new HashSet<String>();

		Subject currentUser = SecurityUtils.getSubject();
		AuthUserVO user = (AuthUserVO) currentUser.getSession().getAttribute(
				"userInfo");

		GeneralUserEntity userEntity = this.sysService.get(
				GeneralUserEntity.class, user.getId());
		if (userEntity != null) {
			List<UserAndRoleEntity> userAndRoleList = userEntity.getRoles();
			for (UserAndRoleEntity ur : userAndRoleList) {
				RoleEntity role = ur.getRole();
				roleNames.add(role.getCode());
				List<RoleAndFunctionEntity> roleAndFunList = role
						.getFunctions();
				for (RoleAndFunctionEntity rf : roleAndFunList) {
					FunctionEntity fun = rf.getFunction();
					permissions.add(fun.getValue());
				}
			}
		} else {
			TSUser tsuser = this.sysService.get(TSUser.class, user.getId());
			List<TSRoleUser> ruList = sysService.findByProperty(
					TSRoleUser.class, "TSUser.id", user.getId());
			for (TSRoleUser ru : ruList) {
				TSRole role = ru.getTSRole();
				roleNames.add(role.getRoleCode());
			}
		}
		List<String> roleList = new ArrayList<String>();
		roleList.addAll(roleNames);
		List<String> funList = new ArrayList<String>();
		funList.addAll(permissions);
		Map<String, List<String>> data = new HashMap<String, List<String>>();
		data.put("roles", roleList);
		data.put("permissions", funList);
		j.setData(data);
		j.setSuccess(true);
		return j;
	}

	@RequestMapping(value = "/saveSelfMessage")
	@ResponseBody
	@RequiresAuthentication
	public ReplyDataMode saveSelfMessage(HttpServletRequest request,
			HttpServletResponse reponse) {
		ReplyDataMode j = new ReplyDataMode();
		// 获取前台传入内容
		String nick = request.getParameter("nick");
		String email = request.getParameter("email");
		if (StringUtil.isEmpty(nick) || StringUtil.isEmpty(email)) {
			j.setStatusCode("信息填写不完整");
			j.setSuccess(false);
			return j;
		}
		Subject currentUser = SecurityUtils.getSubject();
		// 获取当前登录用户
		AuthUserVO user = (AuthUserVO) currentUser.getSession().getAttribute(
				"userInfo");
		GeneralUserEntity userEntity = this.sysService.get(
				GeneralUserEntity.class, user.getId());
		if (userEntity != null) {
			userEntity.setNick(nick);
			userEntity.setEmail(email);
			this.sysService.saveOrUpdate(userEntity);

			// 保存成功
			j.setStatusCode("保存成功");
			j.setSuccess(true);
			return j;
		}
		j.setStatusCode("保存失败,请重试");
		j.setSuccess(false);
		return j;
	}

}
